package cn.spike.rockcc.mq.listener;

import cn.spike.rockcc.domain.CourseOrder;
import cn.spike.rockcc.domain.PayFlow;
import cn.spike.rockcc.domain.PayOrder;
import cn.spike.rockcc.dto.PayMqDto;
import cn.spike.rockcc.service.IPayFlowService;
import cn.spike.rockcc.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author:spike
 * @create:2023-03-23 11:31
 */
@Component
@RocketMQTransactionListener(txProducerGroup = "tx-aliPay")
public class AliPayMQTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IPayFlowService payFlowService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        if(o == null) return RocketMQLocalTransactionState.ROLLBACK;
        PayMqDto payMqDto = JSON.parseObject(JSON.toJSONString(o), PayMqDto.class);
        try {
            PayOrder payOrder = payMqDto.getPayOrder();
            payOrder.setUpdateTime(new Date());
            payOrderService.updateById(payOrder);
            PayFlow payFlow = payMqDto.getPayFlow();
            payFlowService.insert(payFlow);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        PayOrder payOrder = JSON.parseObject(JSON.toJSONString(message), PayOrder.class);
        PayOrder dbPayOrder = payOrderService.selectById(payOrder.getId());

        boolean b = payOrder.getPayStatus().equals(dbPayOrder.getPayStatus());

        if(b) return RocketMQLocalTransactionState.COMMIT;

        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
